package cn.qicaiwang.open.qxyApi.controller;

import cn.qicaiwang.open.common.annotation.Log;
import cn.qicaiwang.open.common.enums.BusinessType;
import cn.qicaiwang.open.common.enums.ResultStatusCodeEnum;
import cn.qicaiwang.open.common.exception.BusinessException;
import cn.qicaiwang.open.common.response.ResponseResult;
import cn.qicaiwang.open.qxyApi.server.EnterpriseInfoService;
import cn.qicaiwang.open.qxyApi.server.QxyApiServer;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * 提供RESTful API接口
 */
@RestController
@RequestMapping("/qcwapp/QxyApi")
public class QxyApiController {


    @Autowired
    private QxyApiServer qxyApiServer;

    @Autowired
    private EnterpriseInfoService enterpriseInfoService;


    /**
     * 通过userId查询企业健康报告次数
     */
    @GetMapping("/reportCount")
    public ResponseResult getReportCount(@RequestParam String userId) {
        try {
            Integer count = qxyApiServer.getReportCount(userId);
            return ResponseResult.ok(count);
        } catch (Exception e) {
            return ResponseResult.error("查询报告次数失败");
        }
    }

    /**
     * 获取企享云AccessToken
     *
     * @return 查验结果
     */
    @GetMapping("/getAccessToken")
    public JSONObject getAccessToken() throws Exception {
        // 从Redis中尝试获取token
        JSONObject accessToken = qxyApiServer.getAccessTokenFromCache();

        if (accessToken == null) {
            // 如果Redis中没有，则调用接口获取
            accessToken = qxyApiServer.refreshAccessToken();
        }

        return accessToken;
    }


    /**
     * 第一步   登录税局发送短信验证码（获取taskId）
     *
     * @return 查验结果
     */
    @Log(title = "登录税局发送短信验证码", businessType = BusinessType.GRANT)
    @PostMapping("/v2/public/login/ext/etaxcookie")
    public ResponseResult etaxcookie(@RequestBody String requestBody) throws Exception {
        JSONObject response = qxyApiServer.etaxCookie(requestBody);
        return ResponseResult.ok(response);
    }


    /**
     * 第二步    登录税局上传短信验证码
     *
     * @return
     */
    @PostMapping("v2/public/login/ext/etaxpushsms")
    @Log(title = "登录税局上传短信验证码", businessType = BusinessType.GRANT)
    public ResponseResult etaxpushsms(
            @RequestBody String requestBody) throws Exception {
        JSONObject response = qxyApiServer.etaxpushsms(requestBody);
        return ResponseResult.ok(response);
    }

    /**
     * 第二步（合并后）   登录税局上传短信验证码并发起企业数据采集
     *
     * @return
     */
    @PostMapping("v2/public/login/ext/pushSmsAndBeginTask")
    @Log(title = "登录税局上传短信验证码并发起企业数据采集", businessType = BusinessType.GRANT)
    public ResponseResult sendMsgAndbeginTask(@RequestBody String requestBody) throws Exception {

        return qxyApiServer.pushSmsAndBeginTask(requestBody);

    }


    /**
     * 第三步    发起企业数据采集(获取taskId)
     *
     * @return
     */
    @PostMapping("v2/collect/beginFinTask")
    @Log(title = "发起企业数据采集", businessType = BusinessType.GRANT)
    public ResponseResult beginFinTask(@RequestBody String request) {
        try {
            boolean response = qxyApiServer.beginFinTask(request);
            return ResponseResult.ok(response);
        } catch (Exception e) {
            return ResponseResult.error("Failed to begin financial task: " + e.getMessage());
        }
    }

    /**
     * 获取采集状态及全量数据
     *
     * @param requestBody 请求JSON字符串
     * @return 标准化响应结果
     */
    @PostMapping("v2/collect/getTaxAndFpInfo")
    @Log(title = "获取采集状态及全量数据", businessType = BusinessType.GRANT)
    public ResponseResult<Boolean> getTaxAndFpInfo(@RequestBody String requestBody, String userId) {
        try {
            // 基础参数校验
            if (StringUtils.isBlank(requestBody)) {
                return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR.getCode(),
                        "请求体不能为空");
            }

            // 调用服务
            boolean result = qxyApiServer.getTaxAndFpInfo(requestBody);

            // 根据布尔值返回不同状态
            return result ?
                    ResponseResult.ok(true) :
                    ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR.getCode(),
                            "任务处理失败", false);

        } catch (BusinessException e) {
            // 已知业务异常
            return ResponseResult.error(e.getCode(), e.getMessage(), false);
        } catch (Exception e) {
            // 未知系统异常

            return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR.getCode(),
                    "系统处理异常，请稍后重试", false);
        }
    }


    // 工商基本信息
    @GetMapping("/bizBasicInfo")
    @Log(title = "工商基本信息", businessType = BusinessType.GRANT)
    public ResponseResult getBizBasicInfo(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getBizBasicInfo(companyName, pageNum, pageSize, userId);
    }

    // 企业联系信息
    @GetMapping("/companyContactInfo")
    @Log(title = "企业联系信息", businessType = BusinessType.GRANT)
    public ResponseResult getCompanyContactInfo(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getCompanyContactInfo(companyName, pageNum, pageSize, userId);
    }


    //股东出资
    @GetMapping("/shareholderInvest")
    @Log(title = "股东出资信息", businessType = BusinessType.GRANT)
    public ResponseResult getShareholderInvest(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getShareholderInvest(companyName, pageNum, pageSize, userId);
    }

    // 对外投资信息
    @GetMapping("/investmentAbroad")
    @Log(title = "对外投资信息", businessType = BusinessType.GRANT)
    public ResponseResult getInvestmentAbroad(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getInvestmentAbroad(companyName, pageNum, pageSize, userId);
    }

    // 税务重大违法信息
    @GetMapping("/taxBigIllegal")
    @Log(title = "税务重大违法信息", businessType = BusinessType.GRANT)
    public ResponseResult getTaxBigIllegal(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getTaxBigIllegal(companyName, pageNum, pageSize, userId);
    }

    // 资质证书信息
    @GetMapping("/certificateInfo")
    @Log(title = "资质证书信息", businessType = BusinessType.GRANT)
    public ResponseResult getCertificateInfo(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getCertificateInfo(companyName, pageNum, pageSize, userId);
    }

    // 失信信息
    @GetMapping("/dishonestyInfo")
    @Log(title = "失信信息", businessType = BusinessType.GRANT)
    public ResponseResult getDishonestyInfo(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getDishonestyInfo(companyName, pageNum, pageSize, userId);
    }

    // 限制高消费信息
    @GetMapping("/limitHighConsumerInfo")
    @Log(title = "限制高消费信息", businessType = BusinessType.GRANT)
    public ResponseResult getLimitHighConsumerInfo(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getLimitHighConsumerInfo(companyName, pageNum, pageSize, userId);
    }

    // 限制高消费关联企业信息
    @GetMapping("/limitHighConsumerRelation")
    @Log(title = "限制高消费关联企业信息", businessType = BusinessType.GRANT)
    public ResponseResult getLimitHighConsumerRelation(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getLimitHighConsumerRelation(companyName, pageNum, pageSize, userId);
    }

    // 裁判文书信息
    @GetMapping("/judgmentDoc")
    @Log(title = "裁判文书信息", businessType = BusinessType.GRANT)
    public ResponseResult getJudgmentDoc(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getJudgmentDoc(companyName, pageNum, pageSize, userId);
    }

    // 欠税公告信息
    @GetMapping("/oweTaxInfo")
    @Log(title = "欠税公告信息", businessType = BusinessType.GRANT)
    public ResponseResult getOweTaxInfo(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getOweTaxInfo(companyName, pageNum, pageSize, userId);
    }

    // 税务非正常户信息
    @GetMapping("/taxUnNormalInfo")
    @Log(title = "税务非正常户信息", businessType = BusinessType.GRANT)
    public ResponseResult getTaxUnNormalInfo(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getTaxUnNormalInfo(companyName, pageNum, pageSize, userId);
    }

    // 行政处罚信息
    @GetMapping("/administrationPenalty")
    @Log(title = "行政处罚信息", businessType = BusinessType.GRANT)
    public ResponseResult getAdministrationPenalty(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getAdministrationPenalty(companyName, pageNum, pageSize, userId);
    }

    // 经营异常名录信息
    @GetMapping("/abnormalBiz")
    @Log(title = "经营异常名录信息", businessType = BusinessType.GRANT)
    public ResponseResult getAbnormalBiz(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getAbnormalBiz(companyName, pageNum, pageSize, userId);
    }

    // 经营异常列入移出公告
    @GetMapping("/removeExceptionList")
    @Log(title = "经营异常列入移出公告", businessType = BusinessType.GRANT)
    public ResponseResult getRemoveExceptionList(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getRemoveExceptionList(companyName, pageNum, pageSize, userId);
    }

    // 严重违法失信企业名单 seriousIllegalBlackInfo
    @GetMapping("/seriousIllegalBlackInfo")
    @Log(title = "严重违法失信企业名单", businessType = BusinessType.GRANT)
    public ResponseResult getSeriousIllegalBlackInfo(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getSeriousIllegalBlackInfo(companyName, pageNum, pageSize, userId);
    }

    // 商标信息
    @GetMapping("/trademarkInfo")
    @Log(title = "商标信息", businessType = BusinessType.GRANT)
    public ResponseResult getTrademarkInfo(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getTrademarkInfo(companyName, pageNum, pageSize, userId);
    }

    // 专利信息
    @GetMapping("/patentInfo")
    @Log(title = "专利信息", businessType = BusinessType.GRANT)
    public ResponseResult getPatentInfo(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getPatentInfo(companyName, pageNum, pageSize, userId);
    }

    // 专利关系信息
    @GetMapping("/patentRelationInfo")
    @Log(title = "专利关系信息", businessType = BusinessType.GRANT)
    public ResponseResult getPatentRelationInfo(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getPatentRelationInfo(companyName, pageNum, pageSize, userId);
    }

    // 专利法律状态信息
    @GetMapping("/patentLawStatus")
    @Log(title = "专利法律状态信息", businessType = BusinessType.GRANT)
    public ResponseResult getPatentLawStatus(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getPatentLawStatus(companyName, pageNum, pageSize, userId);
    }

    // A类纳税人信息
    @GetMapping("/taxpayerLevelA")
    @Log(title = "A类纳税人信息", businessType = BusinessType.GRANT)
    public ResponseResult getTaxpayerLevelA(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getTaxpayerLevelA(companyName, pageNum, pageSize, userId);
    }

    // 行政许可信息
    @GetMapping("/administrativeLicense")
    @Log(title = "行政许可信息", businessType = BusinessType.GRANT)
    public ResponseResult getadministrativeLicense(@RequestParam String companyName, @RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userId) {
        return enterpriseInfoService.getadministrativeLicense(companyName, pageNum, pageSize, userId);
    }

}